#include "file.h"

#include <unistd.h>

using namespace sfc;

namespace sfc::io {

File::File() noexcept : _fd{-1} {}

File::File(fd_t fd) noexcept : _fd{fd} {}

File::File(File&& other) noexcept : _fd{other._fd} {
  other._fd = -1;
}

File::~File() {
  if (_fd == -1) {
    return;
  }
  (void)::close(_fd);
}

auto File::read(Slice<u8> buf) -> usize {
  const auto res = ::read(_fd, buf._ptr, buf._len);
  if (res == -1) {
    throw Error::last_os_error();
  }
  return usize(res);
}

auto File::write(Slice<const u8> buf) -> usize {
  const auto res = ::write(_fd, buf.as_ptr(), buf.len());
  if (res == -1) {
    throw Error::last_os_error();
  }
  return usize(res);
}

}  // namespace sfc::io
